﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Holoville.HOTween;

public partial class MessageScene : Scene
{
	public UIScrollView rewardMessageScrollView;
	public UIGrid rewardMessageGrid;
	public GameObject rewardMessageCell;

	public ObjectPooler rewardMessageObjectPooler; 
	
	Dictionary<int, RewardMessage> rewardMessageDictionary = new Dictionary<int, RewardMessage>();
	Dictionary<int, GameObject> rewardMessageObjectDictionary = new Dictionary<int, GameObject>();
	
	int[] mRewardIndexPathArray;
	bool isEnableGetRewardAll = true;
	
	void RemoveAllRewardMessage()
	{
		rewardMessageDictionary.Clear();
		
		foreach (KeyValuePair<int, GameObject> pair in rewardMessageObjectDictionary)
		{
			NGUITools.SetActive(pair.Value, false);
		}
		rewardMessageObjectDictionary.Clear();
	}

	void LoadRewardMessage()
	{
		RemoveAllRewardMessage();
		
		NetworkManager.Instance.C2S_MSG_LIST<List<RewardMessage>>(3, (responseData) => {
			GameObject g = null;
			int idx = 0;

			ShowBadge(BadgeType.RewardMessage);

			if (responseData.data.Count <= 0)
			{
				NGUITools.SetActive(emptyListView, true);
				return;
			}

			NGUITools.SetActive(emptyListView, false);
			
			responseData.data = responseData.data.OrderByDescending(rewardMessage=>rewardMessage.date).ToList();
			
			foreach (RewardMessage rm in responseData.data)
			{
				g = rewardMessageObjectPooler.GetPooledObject();
				g.transform.parent = rewardMessageGrid.transform;
				g.transform.localScale = Vector3.one;
				g.transform.localRotation = Quaternion.identity;
				
				RewardMessageCell rmc = g.GetComponent<RewardMessageCell>();
				rmc.indexPath = idx;
				// rmc.ouserNameLabel.text = rm.ouserName;
				rmc.receiveDateLabel.text =  DatetimeToString(rm.date);
				rmc.remainTimeLabel.text = DatetimeToFomattedString(rm.date);
				rmc.rewardItemIdLabel.text = GetRewardMessageTitle(rm.msgCategory, rm.keyField, rm.rewardType, rm.rewardItemId, rm.amount);

				NGUITools.SetActive(rmc.getRewardItemButton, false);
				NGUITools.SetActive(rmc.getRewardKinaButton, false);
				NGUITools.SetActive(rmc.getRewardCharacterButton, false);

				switch(rm.rewardType)
				{
				case 1:
					NGUITools.SetActive(rmc.getRewardItemButton, true);
					break;
				case 2:
					NGUITools.SetActive(rmc.getRewardKinaButton, true);
					break;
				case 3:
					break;
				case 4:
					break;
				case 5:
					NGUITools.SetActive(rmc.getRewardCharacterButton, true);
					break;
				}
				
				rewardMessageObjectDictionary.Add (idx, g);
				rewardMessageDictionary.Add (idx, rm);
				
				NGUITools.SetActive(g, true);
				
				idx++;
			}

			rewardMessageGrid.Reposition();
			rewardMessageScrollView.ResetPosition();
		});
	}
	
	public void GetRewardOneProcess(int selectedIndexPath)
	{
		NetworkManager.Instance.C2S_MSG_GET_REWARD(rewardMessageDictionary[selectedIndexPath].id, ( responseData ) => {

			if (responseData.ecode != 0)
			{
				PopupUtility.OneButtonErrorPopup(responseData.ecode);
				return;
			}

			UserData.Instance.userModel = responseData.data;
			
			// 보상이 캐릭터일 경우, 등용 페이지로 바로 이동
			if (rewardMessageDictionary[selectedIndexPath].rewardType == 5)
			{
				SceneController.LoadLevel ("Character_Info");
				return;
			}
			
			HOTween.To (rewardMessageObjectDictionary[selectedIndexPath].transform, 0.5f, new TweenParms().Prop("localPosition", new Vector3(1700.0f, 0.0f, 0.0f), true).Ease(EaseType.EaseInOutQuint).OnComplete( ()=> {
				rewardMessageDictionary.Remove(selectedIndexPath);
				
				NGUITools.SetActive(rewardMessageObjectDictionary[selectedIndexPath], false);
				rewardMessageObjectDictionary.Remove(selectedIndexPath);
				
				rewardMessageGrid.Reposition();	
			}));
		});
	}
	
	
	public void OnClick_GetRewardAll()
	{
		if (rewardMessageDictionary.Count <= 0)
			return;
		
		NetworkManager.Instance.C2S_MSG_GET_ALL_REWARD((responseData) => {
			
			LoadRewardMessage();
			
			if (responseData.ecode != 0)
			{
				PopupUtility.OneButtonErrorPopup(responseData.ecode);
				return;
			}
			
		});
	}

	public void OnClick_RefreshRewardMessage()
	{
		Debug.Log("OnClick_RefreshRewardMessage");
		LoadRewardMessage();
	}

	/*
	 * 재귀적으로 메시지 지우는 로직으로 현재 임시로 사용하지 않음
	 * 
	void GetRewardAll()
	{
		// 이미 GetRewardAll() 진행중이면 끝날때 까지는 추가로 진행하지 않음
		if (isEnableGetRewardAll == false)
		{
			EPLog.Log ("already!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			return;
		}

		// 현재 메시지가 아무것도 없으면 아래 코드를 수행하지 않음
		if (rewardMessageDictionary.Count == 0)
			return;

		int _tempIndex = 0;
		isEnableGetRewardAll = false;

		mRewardIndexPathArray = new int[rewardMessageDictionary.Count];
		foreach (int _key in rewardMessageDictionary.Keys) { mRewardIndexPathArray[_tempIndex++] = _key; }

		GetRewardAllRecursive(0);
	}
	
	void GetRewardAllRecursive(int arrayCurrentIndex)
	{
		int _key = mRewardIndexPathArray[arrayCurrentIndex];
		
		NetworkManager.Instance.C2S_MSG_GET_REWARD(rewardMessageDictionary[_key].id, (responseData) => {
			
			if (responseData.ecode == 0)
			{
				UserData.Instance.userModel = responseData.data;
				
				// 바로 다음 배열의 index가, 배열 마지막 index 값보다 작거나 같을 경우 재귀 호출함
				if (arrayCurrentIndex + 1 <= mRewardIndexPathArray.Length - 1)
				{
					GetRewardAllRecursive(arrayCurrentIndex + 1);
				}
				else
				{
					// 종료조건1 : 현재 가리키는 인덱스(이전 재귀함수에서 1증가시킨 값)가  범위를 벗어났을 경우
					EPLog.Log ("GetRewardAll - End Condition (1)");
					StartCoroutine( DestroyRewardMessageObjects(arrayCurrentIndex) );
				}
			}
			else
			{
				// 종료조건2 : 네트워크 응답 결과 ecode가 0이 아닐 경우
				EPLog.Log ("GetRewardAll - End Condition (2)");
				StartCoroutine( DestroyRewardMessageObjects(arrayCurrentIndex - 1, responseData.ecode) );
			}
			
		});
	}
	
	IEnumerator DestroyRewardMessageObjects(int arrayEndIndex, int ecode = 0)
	{
		EPLog.Log  ("DestroyRewardMessageObjects : " + arrayEndIndex);
		
		if (arrayEndIndex >= 0)
		{
			
			for (int i = 0; i <= arrayEndIndex; i++)
			{
				rewardMessageDictionary.Remove(mRewardIndexPathArray[i]);
				NGUITools.SetActive(rewardMessageObjectDictionary[mRewardIndexPathArray[i]], false);
				rewardMessageObjectDictionary.Remove(mRewardIndexPathArray[i]);
				rewardMessageGrid.Reposition();
				
				if (rewardMessageDictionary.Count == 0)
					NGUITools.SetActive(emptyListView, true);
				
				yield return new WaitForSeconds(0.3f);
			}
		}
		
		if (ecode < 0)
			PopupUtility.OneButtonErrorPopup(ecode);
		
		// GetRewardAll() 과 DestroyRewardMessageObjects() 진행이 끝났으면 관련 값을 가능상태로 바꿈
		isEnableGetRewardAll = true;
		
		yield return null;
	}
	*/
}
